import { onUnmounted, ref } from 'vue';
import axios, { CancelTokenSource } from 'axios';
import {FilterCondition, SortCondition} from '@/components/crud/types';
import {getEntries, StrapiResponse} from "@/api/strapi";


interface TableData {
    // 定义具体字段
    documentId: string;
    // 其他字段...
}
// 获取所有条目
export const useGetEntries = <T>() => {
    const total = ref(0) // 总记录数
    const data = ref<TableData[]>([]);
    const loading = ref(false);
    const error = ref<Error | null>(null);
    let source: CancelTokenSource | null = null;

    function fetch ( contentType: string,
                     page: number = 1, // 默认页码为 1
                     pageSize: number = 25, // 默认每页 25 条记录
                     filters: FilterCondition[] , // 过滤条件
                     sorts: SortCondition[] = [] , // 排序条件
                     fields: string[] = []// 选择的字段
         ) {
        loading.value = true;
        error.value = null;
        source = axios.CancelToken.source();
        getEntries<TableData[]>(
            contentType,
            page,
            pageSize,
            filters,
            sorts,
            fields,
            source
        ).then((res: StrapiResponse<TableData[]>) => {
            data.value = res.data;
            total.value = res.meta?.pagination.total || 0; // 假设接口返回总记录数
        }).finally(() => {
            loading.value = false;
        })
    }

    onUnmounted(() => {
        if (source && loading.value) {
            source.cancel('组件卸载，取消请求');
        }
    });

    return { data, loading, error, fetch , total};
};
